package com.xq.shop.controller.admin;

import java.lang.reflect.Type;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.xq.shop.po.Menu;
import com.xq.shop.po.Privilege;
import com.xq.shop.service.admin.IBaseService;
import com.xq.shop.service.admin.IMenuService;
import com.xq.shop.service.admin.IPrivilegeService;
import com.xq.shop.util.AdminServiceFactory;
import com.xq.shop.util.GsonUtil;
import com.xq.shop.vo.RespMsg;
import com.xq.shop.vo.SearchObject;
import com.xq.shop.vo.RespMsg.Result;

@Controller
@RequestMapping("/admin/")
public class PrivilegeController extends BaseController<Privilege>{

	private IPrivilegeService privilegeService = AdminServiceFactory.getPrivilegeService();
	
	private IMenuService menuService = AdminServiceFactory.getMenuService();
	
	@Override
	public IBaseService<Privilege> getService() {
		return privilegeService;
	}
	
	@RequestMapping("privilege_list.do")
	@ResponseBody
	public String list(SearchObject search){
		
		return GsonUtil.toJson(privilegeService.get(search), Menu.class, new JsonSerializer<Menu>(){

			@Override
			public JsonElement serialize(Menu src, Type typeOfSrc,
					JsonSerializationContext context) {
				JsonObject json = new JsonObject();
				json.addProperty("name", src.getName());
				return json;
			}
		});
	}
	
	@RequestMapping("privilege_edit.do")
	public ModelAndView edit(String id){
		
		ModelAndView modelAndView = new ModelAndView("admin/setting/privilege_edit");
		Privilege privilege;
		if(id != null){
			privilege = privilegeService.get(Long.parseLong(id));
		} else {
			privilege = new Privilege();
		}
		
		if(privilege == null){
			//TODO goto 404
			return modelAndView;
		} else {
			List<Menu> menuList = menuService.getMenu2nd();
			modelAndView.addObject(privilege);
			modelAndView.addObject("menuList", menuList);
			return modelAndView;
		}
	}
	
	@RequestMapping("privilege_save.do")
	public ModelAndView save(Privilege privilege, HttpServletResponse response){
		
		privilegeService.saveOrUpdate(privilege);
		ModelAndView modelAndView = new ModelAndView("admin/setting/privilege_list");
		modelAndView.addObject(new RespMsg(Result.success, "保存成功"));
		return modelAndView;
	}
	
	@RequestMapping("privilege_delete.do")
	public void delete(String id, HttpServletResponse response){
		
		super.delete(id, response);
	}
}
